package com.tanger.permission.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanger.common.enums.EnumIsAble;
import com.tanger.common.enums.EnumYesNo;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.common.utils.StringUtil;
import com.tanger.permission.entity.role.EntityRole;
import com.tanger.permission.entity.vo.RoleQueryVo;
import com.tanger.permission.entity.vo.RoleUpdateVo;
import com.tanger.permission.mapper.role.RoleMapper;
import com.tanger.permission.permission.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @Description 权限实现类
 * @Author Hchenbin
 * @Date 2022/6/28 15:01
 * @Version 1.0
 */
@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleMapper roleMapper;
    private static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);


    @Override
    public EntityRole findRoleById(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    public List<EntityRole> findAll(RoleQueryVo queryVo) {
        List<EntityRole> roles = roleMapper.selectList(
                new QueryWrapper<EntityRole>()
                        .eq(StringUtil.isNull(queryVo.getIsAble())? false:true,"is_able",queryVo.getIsAble())
                        .and(wrapper->wrapper
                                .like(StringUtil.isNull(queryVo.getRoleCode())? false:true,"role_code",queryVo.getRoleCode())
                                .or()
                                .like(StringUtil.isNull(queryVo.getRoleName())? false:true,"role_name",queryVo.getRoleName())));
        return Optional.ofNullable(roles).orElse(new ArrayList<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult saveRole(EntityRole role) {
        if (StringUtil.isNull(role.getId())) return insertRole(role);
        else return updateRole(role);
    }

    @Override
    public ActionResult batchUpdateRole(RoleUpdateVo updateVo) {
        List<EntityRole> roles = new ArrayList<>();
        Arrays.asList(updateVo.getIds()).forEach(x -> {
            EntityRole role = new EntityRole();
            role.setId(x);
            if (updateVo.getStatus().equals(1) || updateVo.getStatus().equals(0)) role.setIsAble(updateVo.getStatus());
            else role.setIsDel(EnumYesNo.yes.getValue());
            roles.add(role);
        });
        int count = roleMapper.batchUpdateRole(roles);
        return count == updateVo.getIds().length ? ActionResult.buildResultSuccess():ActionResult.buildResultError("保存失败");
    }

    @Transactional(rollbackFor = Exception.class)
    ActionResult insertRole(EntityRole role){
        if (roleMapper.selectOne(
                new QueryWrapper<EntityRole>().eq("role_code",role.getRoleCode())) != null)
            return ActionResult.buildResultError("角色编码已存在");
        role.setCreateTime(System.currentTimeMillis());
        role.setIsAble(EnumIsAble.yes.getValue());
        role.setIsDel(EnumYesNo.no.getValue());
        int count = roleMapper.insert(role);
        return count == 1? ActionResult.buildResultSuccess():ActionResult.buildResultError("新增失败");
    }

    @Transactional(rollbackFor = Exception.class)
    ActionResult updateRole(EntityRole role){
        EntityRole orgRole = roleMapper.selectById(role.getId());
        if (orgRole == null) return ActionResult.buildResultError("数据不存在");
        if (!orgRole.getRoleCode().equals(role.getRoleCode()) && roleMapper.selectOne(
                new QueryWrapper<EntityRole>().eq("role_code",role.getRoleCode())) != null)
            return ActionResult.buildResultError("角色编码已存在");
        int count = roleMapper.updateById(BeanUtils.copyProperties(role,orgRole));
        return count == 1? ActionResult.buildResultSuccess():ActionResult.buildResultError("编辑失败");
    }
}
